java一个发生死锁的例子

package com.cal;

class Sock {
static Object A = new Object();
static Object B = new Object();
}

class MyThread3 implements Runnable {
private boolean flag;

public MyThread3(boolean flag){
this.flag = flag;
}

@Override
public void run() {
if(flag){
synchronized(Sock.A){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("if Sock.A");
synchronized (Sock.B) {
System.out.println("if Sock.B");
}
}
} else{
synchronized(Sock.B){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("else Sock.B");
synchronized (Sock.A) {
System.out.println("else Sock.A");
}
}
}
}
}

public class SsTest {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyThread3(false));
Thread thread2 = new Thread(new MyThread3(true));
thread1.start();
thread2.start();
}
}

posted @ 2017-02-06 17:58  小C30  阅读(317)  评论(0编辑  收藏  举报